package com.metaera.app.ui.activities;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.telephony.PhoneNumberFormattingTextWatcher;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.metaera.app.Constants;
import com.metaera.app.LocalConfigStore;
import com.metaera.app.MetaEraApplication;
import com.metaera.app.R;
import com.metaera.app.controller.presenter.LoginPresenter;
import com.metaera.app.controller.view.BasicNetworkRequestView;
import com.metaera.app.controller.view.LoginView;
import com.metaera.app.controller.view.core.INetworkRequestView;
import com.metaera.app.data.model.AppConfigResponse;
import com.metaera.app.data.model.UserDetailsResponse;
import com.metaera.app.ui.core.BaseActivity;
import com.metaera.app.utils.SpannableStringHelper;
import com.metaera.app.utils.ViewUtils;
import com.metaera.app.utils.event.WeChatOAuthCallbackEvent;
import com.metaera.app.utils.validated.EmptyRule;
import com.metaera.app.utils.validated.Length;
import com.metaera.app.utils.validated.Validated;
import com.metaera.app.wxapi.WXEntryActivity;
import com.tencent.mm.opensdk.modelmsg.SendAuth;

import org.greenrobot.eventbus.Subscribe;

import androidx.annotation.Nullable;

// PhoneActionActivity
public class LoginActivity extends BaseActivity implements View.OnClickListener {

    public static Intent newInstance(Activity activity) {
        Intent intent = new Intent(activity, LoginActivity.class);
        intent.putExtra("PAGE_TYPE", 1);
        return intent;
    }

    EditText  et_pwd_fast;
    //   EditText  et_phone_fast;
    TextView  tv_forget_pwd;
    TextView  btn_type_login;
    TextView  phone_action_back;
    Button    btn_login_fast;
    TextView  tv_login_tips;
    ImageView img_right_add_title;

    ViewGroup function_view, pwd_view;


    private TextView tvPhone, tvAgreement;
    private EditText etPhoneFast;

    @Override
    protected int getContentLayoutId() {

        return R.layout.activity_login;
    }

    @Override
    protected void initialize(Bundle savedInstanceState) {
        et_pwd_fast = findViewById(R.id.et_pwd_fast);
//        et_phone_fast = findViewById(R.id.et_phone_fast);
        tv_forget_pwd = findViewById(R.id.tv_forget_pwd);
        btn_type_login = findViewById(R.id.btn_type_login);
        phone_action_back = findViewById(R.id.phone_action_back);
        tv_login_tips = findViewById(R.id.tv_login_tips);
        btn_login_fast = findViewById(R.id.btn_login_fast);
        img_right_add_title = findViewById(R.id.img_right_add_title);

        function_view = findViewById(R.id.function_view);
        pwd_view = findViewById(R.id.pwd_view);
        ViewGroup phoneFast = findViewById(R.id.phone_view);
        tvPhone = findViewById(R.id.tv_phone); // 区号
        tvAgreement = findViewById(R.id.tv_agreement); // 协议
        etPhoneFast = findViewById(R.id.et_phone_fast); // 手机号

        tvPhone.setOnClickListener(this);
        tv_forget_pwd.setOnClickListener(this);
        btn_type_login.setOnClickListener(this);
        img_right_add_title.setOnClickListener(v -> finish());
        phone_action_back.setOnClickListener(v -> finish());

        // init view
        tvPhone.setText(R.string.china_code);
        etPhoneFast.setOnFocusChangeListener((view, b) -> phoneFast.setSelected(b));
        et_pwd_fast.setOnFocusChangeListener((view, b) -> pwd_view.setSelected(b));
        // 显示手机号格式
        etPhoneFast.addTextChangedListener(new PhoneNumberFormattingTextWatcher());

        int pageType = getIntent().getIntExtra("PAGE_TYPE", 0);
        if (pageType == 1) {
            renderForgetPassword();

        } else {
            renderCodeLogin();
        }

        AppConfigResponse config = LocalConfigStore.getInstance().getConfig();
        tvAgreement.setVisibility(config != null ? View.VISIBLE : View.GONE);
        if (config != null){
            tvAgreement.setText(
                    SpannableStringHelper.newBuilder()
                            .append("登录即代表您同意我们的《")
                            .color(Color.parseColor("#A1A1A9"))
                            .append("服务协议")
                            .color(getColorForRes(R.color.colorTextLink))
                            .click(v -> startActivity(WebViewActivity.newIntent(this, config.getTerm_of_service().getValue())))
                            .append("》与《")
                            .color(Color.parseColor("#A1A1A9"))
                            .append("隐私条款")
                            .color(getColorForRes(R.color.colorTextLink))
                            .click(v -> startActivity(WebViewActivity.newIntent(this, config.getPrivacy_policy().getValue())))
                            .append("》")
                            .color(Color.parseColor("#A1A1A9"))
                            .build()
            );
        }



        tvAgreement.setMovementMethod(LinkMovementMethod.getInstance());

        findViewById(R.id.rl_weixin).setOnClickListener(v -> {

            if (!MetaEraApplication.sWxApi.isWXAppInstalled()) {
                Toast.makeText(LoginActivity.this, "您还未安装微信客户端", Toast.LENGTH_SHORT).show();
                return;
            }

            final SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.state = "diandi_wx_login";
            MetaEraApplication.sWxApi.sendReq(req);
            //Intent intent = getIntent();
            //String code = intent.getStringExtra("code");
        });
    }

    @Override
    protected boolean useEventBus() {
        return true;
    }

    private void renderPasswordLogin() { // 账号密码登录
        ViewUtils.setVisibility(View.GONE, tv_login_tips, phone_action_back);
        ViewUtils.setVisibility(View.VISIBLE, pwd_view, tv_forget_pwd);
        btn_type_login.setText(R.string.login_code_login);
        btn_login_fast.setText(R.string.login);

        Validated.add(btn_login_fast, new EmptyRule(etPhoneFast), new EmptyRule(et_pwd_fast));

        // 登录
        LoginPresenter presenter = new LoginPresenter();
        presenter.setModelAndView(new BasicNetworkRequestView<>(new LoginView(this)));
        btn_login_fast.setOnClickListener(v -> presenter.password(etPhoneFast.getText(), et_pwd_fast.getText()));

        tv_forget_pwd.setOnClickListener(v -> startActivity(LoginActivity.newInstance(this)));
    }

    private void renderCodeLogin() { // 验证码登录
        ViewUtils.setVisibility(View.VISIBLE, tv_login_tips);
        ViewUtils.setVisibility(View.GONE, pwd_view, tv_forget_pwd, phone_action_back);
        btn_type_login.setText(R.string.login_password_login);
        btn_login_fast.setText(R.string.login_get_code);

        Validated.add(btn_login_fast, new EmptyRule(etPhoneFast));

        // 获取验证码
        btn_login_fast.setOnClickListener(v ->
                startActivity(VerifyCodeActivity.newInstance(this,
                        etPhoneFast.getText(), tvPhone.getText(), VerifyCodeActivity.AUTH_CODE_TYPE)));
    }


    // 忘记密码页面
    private void renderForgetPassword() {
        ViewUtils.setVisibility(View.VISIBLE, tv_login_tips);
        ViewUtils.setVisibility(View.GONE, function_view, tv_forget_pwd, tvAgreement, pwd_view, img_right_add_title);
        tv_login_tips.setText("通过验证注册手机号即可重新设置新密码");
        btn_login_fast.setText(R.string.login_get_code);

        Validated.add(btn_login_fast, new EmptyRule(etPhoneFast));

        // 获取验证码
        btn_login_fast.setOnClickListener(v ->
                startActivity(VerifyCodeActivity.newInstance(this,
                        etPhoneFast.getText(), tvPhone.getText(), VerifyCodeActivity.FORGET_TYPE)));
    }

    // 微信
//    private void renderBindMobile() {
//        phone_action_back.setVisibility(View.VISIBLE);
//        ViewUtils.setVisibility(View.GONE, pwd_view, tv_forget_pwd, function_view, tvAgreement, img_right_add_title);
//        Validated.add(btn_login_fast, new EmptyRule( etPhoneFast));
//        btn_login_fast.setOnClickListener(v ->
//                startActivity(VerifyCodeActivity.newInstance(this,
//                etPhoneFast.getText(), tvPhone.getText(), VerifyCodeActivity.BIND_WX_TYPE)));
//    }


    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.tv_phone) { // 选择手机号地区
//            startActivity(new Intent(this, PhoneNumberPickActivity.class));
            startActivityForResult(new Intent(this, PhoneNumberPickActivity.class), Constants.REQ_ARE_CODE);

        } else if (view.getId() == R.id.tv_forget_pwd) { // 忘记密码
            startActivity(new Intent(this, LoginActivity.class));

        } else if (view.getId() == R.id.btn_type_login) { // 登录类型切换
            if (tv_forget_pwd.getVisibility() == View.GONE) {
                renderPasswordLogin();

            } else {
                renderCodeLogin();
            }
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK && requestCode == Constants.REQ_ARE_CODE && data != null) {
            int code = data.getIntExtra(Constants.EXTRA_AREA_CODE, 86);
            tvPhone.setText("+" + code);
        }
    }

    @Subscribe
    public void onEvent(WeChatOAuthCallbackEvent event) {
        LoginPresenter presenter = new LoginPresenter();
        presenter.setModelAndView(new BasicNetworkRequestView<>(new LoginView(this) {
            @Override
            public void successful(UserDetailsResponse data) {
                if (TextUtils.isEmpty(data.getMobile())) { // 没有绑定手机号

                    phone_action_back.setVisibility(View.VISIBLE);
                    ViewUtils.setVisibility(View.GONE, pwd_view, tv_forget_pwd, function_view, tvAgreement, img_right_add_title);
                    Validated.add(btn_login_fast, new EmptyRule( etPhoneFast));
                    btn_login_fast.setOnClickListener(v ->
                            startActivity(VerifyCodeActivity.newInstance(LoginActivity.this,
                                    etPhoneFast.getText(), tvPhone.getText(), data.getToken())));

                } else {

                    super.successful(data);
                }
            }
        }));

        presenter.wx(event.getCode());

    }

}
